function ismobile() {
    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                qq: u.match(/\sQQ/i) == " qq" //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };
    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
};

//$(function () {

var useCoupon, address, $uid, token, obj, lists, ids;

//getSettlementId();

//getListData(
//    28,
//    "178AAB3E-2B5B-D348-C3EA-B3B0ADAF65F1",
//    [
//        {"cart_id": 74, "clear_number": 2, "end_time": 201807231900, "start_time": 201807231600},
//        {"cart_id": 73, "clear_number": 1, "end_time": 201807231900, "start_time": 201807231500}
//    ]
//    //[69, 68]
//)

//});
var isMobile = ismobile();

function getSettlementId() {

    if (isMobile == 1) {

        CallOrderDetailsModel.jsCallOCWithSendId("Data");

    } else if (isMobile == 0) {

        window.android.getAndroidOrderId("okok")
    }
}

if (isMobile == 0) {

    window.android.getAndroidOrderId("okok")
}

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);
}

function receiveiOSVcData(i) {

    obj = $.parseJSON(i);

    $uid = obj.uid;

    token = obj.TOKEN;

    lists = obj.clear_list;

    ids = [];

    lists.forEach(function (item, i) {

        ids.push(item.cart_id)

    });

    getListData($uid, token, lists, ids)
}

function receive_android_orderId(k) {

    obj = $.parseJSON(k);

    $uid = obj.uid;

    token = obj.TOKEN;

    lists = obj.clear_list;

    ids = [];

    lists.forEach(function (item, i) {

        ids.push(item.cart_id)

    });
    //alert(ids)
//alert(JSON.stringify(lists))
    getListData($uid, token, lists, ids)

}

function getListData(uid, token, lists, ids) {

    $.ajax({

        type: "POST",

        url: url + "users/fourModel",

        dataType: "json",

        data: {

            "url": "cart/clearing",

            "uid": uid,

            "clear_list": lists//数组
        },
        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token)
        },
        success: function (data) {

            //console.log(data);

            if (data.codes == 200) {

                var list = data.data.list;

                var html = template("settlementTpl", data);

                $("#order_body").html(html);

                defaultAddress(uid);

                if (isiphoneX) {

                    $("#order_footer").css("padding-bottom", "0.484rem");


                    $("#order_section").css("padding-bottom", "0.484rem")
                }

                var typeList = [];

                list.forEach(function (item, i) {

                    typeList.push(item.goods_info.belong_model);

                    $(".date" + i).html("日期：" + timeFormat(item.choose_start_time).slice(5) + " ~ " + timeFormat(item.choose_end_time).slice(5))

                });




                //点击添加地址

                $(".order_address").on("click", function () {

                    clickAddAddress();
                });
                //点击优惠券
                $(".order_coupon").on("click", function () {

                    clickCoupon(typeList, data);
                });
                //点击提交
                var isTrue = true;

                $(".submit").on("click", function () {

                    if (isTrue) {

                        clickSubmit(data, token, ids);

                        isTrue = false;
                    }
                    setTimeout(function () {

                        isTrue = true

                    }, 1500)
                });


                //var ProductAmount = list.map(function (item, i) {
                //
                //    var a = 0;
                //
                //    a += Number(item.goods_price * lists[i].clear_number);
                //
                //    return a
                //});
                //
                //var ProductAmounta = eval(ProductAmount.join('+'));
                //
                //$(".proTotal").html(ProductAmounta);                                //产品金额
                //
                //var couponPrice = $(".couponPrice").html() || 0;                  //优惠券
                //
                //var deposit = $(".cash_pledge").html();                             //押金
                //
                //var freight = $(".sendTotal").html();                               //运费

                //$(".order_price").html("实付款:￥" + (Number(ProductAmounta) + Number(deposit) + Number(freight) - Number(couponPrice)));//总价


            } else {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                        "VcData": data.msg,
                        "VcWay": "ShowMessage"
                    });

                    //CallOrderDetailsModel.jsCalliOSWithShowMessage(data.msg);

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.msg);
                }
            }


        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallOrderDetailsModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");

            }
        }
    })
}

function defaultAddress(uid) {//获取默认地址

    $.ajax({

        url: url + "users/fourModel",

        type: "POST",

        dataType: "json",

        data: {
            "url": "address/lists",

            "uid": uid,

            "addr_type": 1
        },

        success: function (data) {

            if (data.codes == 200) {

                var list = data.data.list[0];

                $(".address_contacts b ").html(list.link_man);

                $(".address_phone").html(list.link_mobile);

                $(".serviceAddress b").html(list.shipping_address);

                //$(".address .defultaddr").css("display", "block");

                $(".address").css("margin-left", "0");

                //$(".order_address").attr("data-type", "100");

            } else {

                //$(".order_address").attr("data-type", "200");

            }

        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallOrderDetailsModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");

            }
        }
    });
}

function clickXieyi() {//点击协议

    var json = {
        "url": "https://viewapi.aipics.cn/view_h5/agreement/lease.html",

        "titleName": "用户租赁协议"
    };

    if (isMobile == 1) {

        var message = {

            "VcData": json,

            "VcName": "PublicWeb",

            "VcWay": "PushVCName"
        };

        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);

    } else if (isMobile == 0) {

        window.android.toRule("...")
    }
}
//接收  订单收货地址
var address1 = "", address2 = "", address3 = "", address4 = "", contacts1 = "", contacts = "", iphone = "", iphone1 = "";

function receiveiOSAddAddress(a) {

    var result = JSON.parse(a);

    address1 = $(".serviceAddress b").html(result['shipping_address']);

    //address2=a.addressDetails;

    //address3=a.addressTitle;

    contacts = result.link_man;

    iphone = result.link_mobile;

    contacts1 = $(".address_contacts b").html(result['link_man']);

    iphone1 = $(".address_phone").html(result['link_mobile']);

    $(".address").css("margin-left", "0");

}

function receive_android_addAddress(k) {

    var result = JSON.parse(k);

    address1 = $(".serviceAddress b").html(result.province + result.city +result.district+ result.address);

    address2 = result.province;

    address3 = result.city;

    address4 = result.address;

    contacts = result.contacts;

    iphone = result.iphone;

    contacts1 = $(".address_contacts b").html(result.contacts);

    iphone1 = $(".address_phone").html(result.iphone);

    $(".address").css("margin-left", "0");

}

function clickAddAddress() {//点击添加地址

    if (isMobile == 1) {

        var message = {

            "VcData": {

                "addressTitle": address3,

                "addressDetails": address2,

                "contacts": contacts,

                "iphone": iphone
            },

            "VcName": "AddressManager",

            "VcWay": "AddAddress"
        };

        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);



    } else if (isMobile == 0) {

        var json = {

            "address": address4,

            "province": address2,

            "city": address3,

            "contacts": contacts,

            "iphone": iphone
        };

        window.android.jumpToProjectAdress(JSON.stringify(json));
    }
}

function clickCoupon(typeList, data) {//点击选择优惠券

    var type = 0;

    var res = [10];

    if (typeList.length >= 2) {

        type = typeList[0];

        for (var i = 0; i < typeList.length - 1; i++) {

            if (type == typeList[i + 1]) {

                res.push(type)
            }
            else {

                res.pop();

                res = [10];

                break;
            }
        }

    } else {

        res.push(typeList[0]);
    }

    var json = {

        "uid": $uid,

        "Tprice": data.data.goods_price_total_count_except_deposit,

        "type": res

    };

    if (isMobile == 1) {

        var message = {

            "VcData": json,

            "VcWay": "OrderCoupons"
        };

        window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);

        //CallOrderDetailsModel.jsCalliOSWithOrderCoupons({"VcData": json});

    } else if (isMobile == 0) {

        window.android.showCoupon(JSON.stringify(json));
    }
}
//接收优惠券信息

function receiveiOSOrderCoupon(a) {

    var obj = $.parseJSON(a);

    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.id);

        var money = $(".proTotal").html();//商品价格

        var sendTotal = Number($(".sendTotal").html());//运费

        var cash_pledge = Number($(".cash_pledge").html());//押金

        var couponPrice = Number(obj.face) || 0;//优惠券

        $(".order_price").html("实付款:￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));//总价

        //$("#order_footer .order_price").html("￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));//总价

        $(".coupon_pledge").html(couponPrice);//优惠金额

    } else {

        useCoupon = 100;

        $(".couponPrice").html("请选择");

    }

}

function receive_android_orderCoupon(k) {

    var obj = $.parseJSON(k);

    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.cid);

        var money = $(".proTotal").html();//商品价格

        var sendTotal = Number($(".sendTotal").html());//运费

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseInt($(".insurance").html());// 保险

        var couponPrice = Number(obj.face) || 0; //优惠券

        $(".order_price").html("实付款:￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));//总价

        $(".coupon_pledge").html(couponPrice);//优惠金额

    } else {

        useCoupon = 100;

        $(".couponPrice").html("请选择");
    }

}
//格式化时间
function timeFormatDate(timeStamp) {

    var tmpTime = Date.parse(new Date(timeStamp));

    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    var newDate = new Date();
    newDate.setTime(tmpTime);
    return newDate.format('yyyyMMddhhmm');
}

function timeFormat(time) {//201712271200
    var y = time.substring(0, 4);
    var m = time.substring(4, 6);
    var d = time.substring(6, 8);
    var h = time.substring(8, 10);
    var s = time.substring(10, 12);
    return (y + "-" + m + "-" + d + " " + h + ":" + s);
}

function check(uid, token, list, orderData, ids) {
    
    //console.log(list)

    var totalMoney = $(".order_price").html().slice(5);

    var receiveName = $(".address_contacts b").html();

    var receivePhone = $(".address_phone").html();

    //var address = orderData.data.list[0].area_info.id;

    var address = $(".serviceAddress b").html();

    $.ajax({

        type: "POST",

        url: url + "users/fourModel",

        dataType: "json",

        data: {

            "url": "check/batchGoodsWarehouse",

            "list": list,

            "uid": uid
        },
        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token)
        },
        success: function (data) {

            //console.log(data)

            if (data.codes == 200) {

                var cid = $(".order_coupon").attr("id");//获取优惠券id

                if (cid) {

                    orderMake($uid, Number(totalMoney), receiveName, Number(receivePhone), address, orderData, token, 200, ids, cid)

                } else {

                    orderMake($uid, Number(totalMoney), receiveName, Number(receivePhone), address, orderData, token, 100, ids)
                }
            } else {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({"VcData": data.msg, "VcWay": "ShowMessage"});

                    //CallOrderDetailsModel.jsCalliOSWithShowMessage(data.msg);

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.msg);

                }
            }

        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({"VcData": "请检查网络", "VcWay": "ShowMessage"});

                //CallOrderDetailsModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");

            }
        }
    })
}

function clickSubmit(data, token, ids) {//点击提交

    var list = [];

    list.length = data.data.list.length;

    data.data.list.forEach(function (item, i) {

        list[i] = {};

        list[i].goods_id = item.goods_id;

        list[i].need_address_id = item.need_addr_id;

        list[i].need_number = item.goods_number;

        list[i].meal_type = item.meal_info.meal_type;

        list[i].start_time = item.choose_start_time.replace(/-/g, "/");

        list[i].end_time = item.choose_end_time.replace(/-/g, "/");

        list[i].meal_id = item.meal_info.id;
    });

    if ($(".address_phone").html().length > 0) {
        
        //console.log(list)

        check($uid, token, list, data, ids);

    } else {
        if (isMobile == 1) {

            window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({"VcData": "请选择或设置服务地址", "VcWay": "ShowMessage"});

            //CallOrderDetailsModel.jsCalliOSWithShowMessage("请选择或设置服务地址");

        } else if (isMobile == 0) {

            window.android.toastMsg("请选择或设置服务地址");

        }
    }


}

function orderMake(uid, money, name, mobile, addr, data, token, useCoupon, ids, couponId) {

    var obj = [];

    data.data.list.forEach(function (item, i) {

        obj[i] = {};

        obj[i].goods_id = item.goods_id;

        obj[i].need_number = item.clear_number;

        obj[i].start_time = item.choose_start_time.replace(/-/g, "/");

        obj[i].end_time = item.choose_end_time.replace(/-/g, "/");

        obj[i].need_addr_id = item.need_addr_id;

        obj[i].meal_id = item.meal_id;

        obj[i].belong_model = item.goods_info.belong_model;

        obj[i].time_long_id = item.time_long_id

    });

    $.ajax({

        type: "POST",

        url: url + "users/ordermake",

        dataType: "json",

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        data: {

            "uid": uid,

            "total_money": money,

            "receive_user_name": name,

            "receive_user_mobile": mobile,

            "receive_user_addr": addr,

            "use_coupon": useCoupon,

            "coupon_id": couponId, //优惠券  默认值为100 如果有优惠券传递200，还有优惠券id

            "clear_cart_ids": ids,

            "order_info": obj
        },
        success: function (data) {

            //console.log(data.codes);

            if (data.codes == "200") {

                if (isMobile == 1) {

                    var message = {

                        "VcData": {

                            "order_code": data.data.order_code
                        },

                        "VcName": "ListPay",

                        "VcWay": "PushVCName"
                    };

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage(message);

                    //CallOrderDetailsModel.jsCalliOSWithPushVCName({
                    //
                    //    "VcData": {
                    //
                    //        "order_code": data.data.order_code
                    //    },
                    //    "VcName": "ListPay"
                    //});
                } else if (isMobile == 0) {

                    window.android.jumptoOrderActivity(data.data.order_code);

                }
            } else if (data.codes != "200" && data.codes) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({"VcData": data.msg, "VcWay": "ShowMessage"});

                    //CallOrderDetailsModel.jsCalliOSWithShowMessage(data.msg);

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.msg);

                }

            } else if (data.codes == null) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({"VcData": "系统繁忙，请稍后重试", "VcWay": "ShowMessage"});

                    //CallOrderDetailsModel.jsCalliOSWithShowMessage("系统繁忙，请稍后重试");

                } else if (isMobile == 0) {

                    window.android.toastMsg("系统繁忙，请稍后重试");

                }
            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDetailsModel.postMessage({"VcData": "请检查网络", "VcWay": "ShowMessage"});

                //CallOrderDetailsModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");

            }
        }
    });
}
